<?php

namespace App\Events;

use App\Models\Oauth;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Session;
use Overtrue\Socialite\User;

class WechatRegister
{

    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @param User $user
     */
    public function __construct()
    {
        $user = Session::get("wechat.oauth_user.default");
        if ($user&&$user['id']){
            $openid = $user['id'];
            $oauth = Oauth::findUser("wx_account",$openid);
            $nickname = $user['nickname'];
            $avatar = $user['avatar'];
            if (!$oauth){
                $userInfo = new \App\Models\User();
                $userInfo->nickname = $nickname;
                $userInfo->avatar = $avatar;
                $res = $userInfo->save();
                if ($res){
                    Oauth::addData($userInfo->id,$openid,$nickname);
                }
            }else{
                $userInfo = \App\Models\User::find($oauth->user_id);
                if ($oauth->openname!= $nickname){
                    $oauth->openname = $nickname;
                    $oauth->save();
                }
                if($userInfo->nickname!=$nickname||$userInfo->avatar!=$avatar){
                    $userInfo->nickname = $nickname;
                    $userInfo->avatar =$avatar;
                    $userInfo->save();
                }
            }
            Session::put("wechat.userInfo",$userInfo);
        }else{
            Session::forget("wechat.oauth_user.default");
        }
    }


}
